package dispatchers;

import java.io.*;
import java.sql.*;
import util.*;
import objects.*;
import java.util.*;

public class DBWordDispatcher{
	private DBManager dbManager;
	private String tableName;

	public DBWordDispatcher(DBManager dbManager, String tableName){
		this.dbManager = dbManager;
		this.tableName = tableName;
	}
	
	private Statement getStatement(){
		try{
			return dbManager.getConnection().createStatement();
		}catch(SQLException e){
			System.out.println(e);
			return null;
		}
	}
	
	
	public List<String> getWords(){	
		String query = "SELECT word FROM " + tableName + ";";
		
		ResultSet resultSet;
		LinkedList<String> wordList = new LinkedList<String>();
		try{
			resultSet = getStatement().executeQuery(query);	
			
			while(resultSet.next()){
				wordList.add(resultSet.getString("word"));
			}
		}catch(SQLException e){
			System.out.println(e);
			return null;
		}
		return wordList;
	}
	
	
	public boolean addWord(String word){
		String query = "INSERT INTO " + tableName + " (word) VALUES(\'"+word+"\');";
		
		try{
			int n = getStatement().executeUpdate(query);	
			if(n==1)
				return true;
			else return false;
		}catch(SQLException e){
			System.out.println(e);
			return false;
		}
	}
	

	public boolean removeWord(String word){
		String query = "DELETE FROM " + tableName + " WHERE word = \'"+word+"\' LIMIT 1 ;";
		
		try{
			int n = getStatement().executeUpdate(query);	
			if(n==1)
				return true;
			else return false;
		}catch(SQLException e){
			System.out.println(e);
			return false;
		}
	}
	

	
	public String getRandomWord(){
		String query = "SELECT MAX(wordID) FROM "
			+tableName+" ;";  //запрос на получения максимального индекса у слов
		
		int max=0;
		String word=null;
		ResultSet resultSet;
		try{
			resultSet = getStatement().executeQuery(query);	
			if(!resultSet.next()){
				System.out.println("post not found");
				return null;
			}
			max = resultSet.getInt(1);
			Random rand = new Random(System.currentTimeMillis());
			
			query = "SELECT word FROM "
				+tableName+" WHERE wordID >= "+(rand.nextInt(max)+1)+" LIMIT 1;";  //запрос на случайную строку
			
			resultSet = getStatement().executeQuery(query);	
			if(!resultSet.next()){
				System.out.println("word not found");
				return null;
			}
			return resultSet.getString("word");
			
		}catch(SQLException e){
			System.out.println(e);
			return null;
		}
	}
	
	
	public static void main(String []arg){
		DBWordDispatcher pd = new DBWordDispatcher(new DBManager("anagram", "root", "root"), "words");
		pd.addWord("america");
		pd.addWord("america");
		
		pd.removeWord("america");
		
		List list = pd.getWords();
		for(int i=0; i<list.size(); i++)
			System.out.println(list.get(i));
	}
}